package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.mapper.CourseMapper;
import com.example.demo.entity.Course;
import com.example.demo.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class AddCourseController {
    @Autowired
    private CourseMapper cm;
    @RequestMapping("addcourse")
    public void addCourse(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        int courseid=Integer.valueOf(request.getParameter("courseid"));
        int id=Integer.valueOf(request.getParameter("id"));
        String teachername=request.getParameter("teachername");
        String coursename=request.getParameter("coursename");
        int type=Integer.valueOf(request.getParameter("type"));
        int time=Integer.valueOf(request.getParameter("time"));
        Float gredit=Float.valueOf(request.getParameter("gredit"));
        String term=request.getParameter("term");
        String begintime=request.getParameter("begintime");
        String endtime=request.getParameter("endtime");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date begt = null;
        try {
            begt = df.parse(begintime);
            Date endt= df.parse(endtime);
            Course cou=new Course(courseid,id,teachername,coursename,type,time,gredit,term,begt,endt);

            List<Course> list =new ArrayList<Course>();
            list=cm.findAlllCourse();
            boolean isIdExist=list.stream().anyMatch(course -> course.getId()==id);
            boolean isTeacherNameExist=list.stream().anyMatch(course -> course.getTeachername().equals(teachername) &&
                    course.getTeachername().equals(coursename));
            String regex = "^20\\d{2}-20\\d{2}-[1,2]$";
            boolean isValidTerm = term.matches(regex);
            if (isIdExist ||  isTeacherNameExist || isValidTerm) {
                response.getWriter().write(JSONObject.toJSONString(Message.failure("Input date is illegal.")));
            }
            int n=cm.insertCou(cou);
            if(n>0){
                response.getWriter().write(JSONObject.toJSONString(Message.success("Success add")));
            }else{
                response.getWriter().write(JSONObject.toJSONString(Message.failure("Failure add")));
            }
        } catch (ParseException e) {
            response.getWriter().write(JSONObject.toJSONString(Message.failure("Input date is illegal.")));
        }
    }
}
